package tazmania;

import javax.media.opengl.GL;
import javax.media.opengl.GL2;

public class SparkLine {
	public static void draw(final GL2 gl, final float x0, final float y0, final float x1, final float y1, final float amount) {
		final float length = (float) Math.sqrt((x0 - x1) * (x0 - x1) + (y0 - y1) * (y0 - y1));
		final float ilength = 1.0f / length;

		final float dx = (x1 - x0) * ilength;
		final float dy = (x1 - x0) * ilength;
		final float nx = dy;
		final float ny = -dx;

		gl.glBegin(GL.GL_LINE_STRIP);
		gl.glVertex2f(x0, y0);
		split(gl, x0, y0, x1, y1, nx, ny, 5, amount + 0.1f);
		gl.glVertex2f(x1, y1);
		gl.glEnd();
	}

	private static void split(final GL2 gl, final float x0, final float y0, final float x1, final float y1, final float nx, final float ny,
			final int iter, final float amount) {
		if (iter <= 0) {
			return;
		}

		final float midx = (x1 - x0) / 2 + x0 + nx * ((float) Math.random() - 0.5f) * amount * 200;
		final float midy = (y1 - y0) / 2 + y0 + ny * ((float) Math.random() - 0.5f) * amount * 200;

		split(gl, x0, y0, midx, midy, nx, ny, iter - 1, amount * 0.5f);
		gl.glVertex2f(midx, midy);
		split(gl, midx, midy, x1, y1, nx, ny, iter - 1, amount * 0.5f);
	}
}
